﻿using Common;
using DbUtility;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Areas.Admin.Lib;

namespace Web.Areas.Admin.Controllers
{
    public class ExpertController : BaseController
    {
        public ActionResult Index(ExpertSearch search)
        {
            expertLogic el = new expertLogic();
            playerLogic pl = new playerLogic();
            scorelogLogic sl = new scorelogLogic();
            var list = el.Getexperts(new expert(), PageIndex, PageSize, search.GenerateWhere(), "createdate", "desc");
            var currentPlayer = pl.Getplayer(new player { isopen = true }) ?? new player();
            foreach (var item in list.PageList)
            {
                var dbLog = sl.Getscorelog(new scorelog { playerid = currentPlayer.id, userid = item.userid }) ?? new scorelog();
                item.Score = dbLog.score == 0 ? "" : dbLog.score.ToString();
                item.Player = currentPlayer.id > 0 ? currentPlayer.sort + "号选手 " + currentPlayer.name : "";
            }

            if (Request.IsAjaxRequest())
            {
                return PartialView("_Index", list);
            }
            return View(list);
        }

        public ActionResult Create()
        {
            expert expert = new expert();
            return View(expert);
        }
        [HttpPost]
        public ActionResult Create(expert expert)
        {
            try
            {
                wx_usersLogic ul = new wx_usersLogic();
                expertLogic el = new expertLogic();
                var dbExpert = el.Getexpert(new expert { mobile = expert.mobile });
                if (dbExpert != null)
                {
                    return ErrorMsg("手机号码重复！");
                }
                expert.createdate = DateTime.Now;
                expert.createuserid = Account.ID;
                var result = el.Create(expert);
                if (result > 0)
                {
                    expert.id = result;
                    var dbUser = ul.Getwx_users(new wx_users { mobile = expert.mobile });
                    if (dbUser != null)
                    {
                        dbUser.type = (int)UserType.Expert;
                        var r = ul.Update(dbUser);
                        if (r)
                        {
                            expert.userid = dbUser.id;
                            el.Update(expert);
                        }
                    }
                    return SuccessMsg("创建成功！");
                }
                else
                {
                    return ErrorMsg("创建失败，网络错误！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        public ActionResult Edit(int id)
        {
            expertLogic el = new expertLogic();
            var dbExpert = el.Getexpert(id);
            return View(dbExpert);
        }
        [HttpPost]
        public ActionResult Edit(expert expert)
        {
            try
            {
                wx_usersLogic ul = new wx_usersLogic();
                expertLogic el = new expertLogic();
                var dbExperts = el.Getexperts(new expert { mobile = expert.mobile }, string.Format(" and id!={0}", expert.id));
                if (dbExperts.Count > 0)
                {
                    return ErrorMsg("手机号码重复！");
                }
                expert.modifydate = DateTime.Now;
                expert.modifyuserid = Account.ID;
                var result = el.Update(expert);
                if (result)
                {
                    var dbUser = ul.Getwx_users(new wx_users { mobile = expert.mobile });
                    if (dbUser != null)
                    {
                        dbUser.type = (int)UserType.Expert;
                        var r = ul.Update(dbUser);
                        if (r)
                        {
                            expert.userid = dbUser.id;
                            el.Update(expert);
                        }
                    }
                    return SuccessMsg("编辑成功！", expert.id);
                }
                else
                {
                    return ErrorMsg("编辑失败，网络错误！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
        [HttpPost]

        public ActionResult Delete(int id)
        {
            try
            {
                DBContext db = new DBContext();
                wx_usersLogic ul = new wx_usersLogic();
                expertLogic el = new expertLogic();
                var dbExpert = el.Getexpert(id);
                if (dbExpert == null)
                {
                    return ErrorMsg("专家不存在或已删除！");
                }
                var result = el.Delete(dbExpert);
                if (result)
                {
                    if (dbExpert.userid > 0)
                    {
                        db.ExecuteNonQuerySql(string.Format("UPDATE dbo.wx_users SET type = {0} WHERE id = {1}", (int)UserType.Public, dbExpert.userid));
                    }
                    return SuccessMsg("删除成功！");
                }
                else
                {
                    return ErrorMsg("删除败，网络错误！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        public ActionResult ExportAll()
        {
            try
            {
                DBContext db = new DBContext();
                var dataTable = db.ExecuteDataTableSql("SELECT id,createdate,name,mobile,CASE userid WHEN 0 THEN '否' ELSE '是'  END AS isbind FROM dbo.expert WHERE isdeleted=@isdeleted", new List<System.Data.Common.DbParameter>()
                {
                    new System.Data.SqlClient.SqlParameter("@isdeleted",false){SqlDbType=System.Data.SqlDbType.Bit},
                });
                var dic = new Dictionary<string, string>
                {
                    {"name", "专家姓名"},
                    {"mobile", "手机号码"},
                    {"isbind", "是否已认证"},
                };
                ExcelHelper.DataTableToExcel(dataTable, dic, "专家列表" + DateTime.Now.Format("yyyyMMddHHmmss"));
                return Content("");
            }
            catch (Exception ex)
            {
                return ErrorMsg(ex.Message);
            }
        }
    }
}
